<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
				<el-button class="uni-button" type="default" size="mini" @click="navigateTo('./statistics')">统计信息</el-button>
				<button class="uni-button" type="default" size="mini" v-if="false" @click="delTable">批量删除</button>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query.keyword" placeholder="请输入搜索内容" />
				<el-select v-model="query.type" clearable placeholder="请选择服务类型"><el-option v-for="(item, inx) in typeMap" :key="inx" :label="item" :value="inx"></el-option></el-select>
				<el-select v-model="query.service_location" clearable placeholder="请选择地点"><el-option v-for="(item, inx) in typeLocalMap" :key="inx" :label="item" :value="inx"></el-option></el-select>
				<el-select v-model="query.status" clearable placeholder="请选择订单状态"><el-option v-for="(item, inx) in filtMap" :key="inx" :label="item" :value="inx"></el-option></el-select>
				<el-select v-model="query.pay_type" clearable placeholder="请选择支付方式"><el-option v-for="(item, inx) in paytTypeMap" :key="inx" :label="item" :value="inx"></el-option></el-select>
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db
				ref="udb"
				:collection="collectionName"
				:options="options"
				:where="where"
				page-data="replace"
				:orderby="orderby"
				:getcount="true"
				:page-size="options.pageSize"
				:field="fields"
				:page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error }"
			>
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" fixed>用户信息</uni-th>
						<uni-th align="center">护工信息</uni-th>
						<uni-th align="center">患者姓名</uni-th>
						<uni-th align="center">服务类型</uni-th>
						<uni-th align="center">服务地点</uni-th>
						<uni-th align="center">订单状态</uni-th>
						<uni-th align="center">患者年龄</uni-th>
						<uni-th align="center">联系电话</uni-th>
						<uni-th align="center">订单总金额</uni-th>
						<uni-th align="center">服务开始时间</uni-th>
						<uni-th align="center">服务结束时间</uni-th>
						<uni-th align="center">服务天数</uni-th>
						<uni-th align="center">服务小时</uni-th>
						<uni-th align="center">天数总和</uni-th>
						<uni-th align="center">小时总和</uni-th>
						<uni-th align="center">开始小时</uni-th>
						<uni-th align="center">结束小时</uni-th>
						<uni-th align="center">支付方式</uni-th>
						<uni-th align="center">下单平台类型</uni-th>
						<uni-th align="center">订单创建时间/发起退款时间</uni-th>
						<uni-th align="center">订单付款时间</uni-th>
						<uni-th align="center">微信或支付宝交易单号</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">
							<view v-for="(nick, nix) in item.user_id" :key="nix">{{ nick.nickname }}</view>
						</uni-td>
						<uni-td align="center">
							<view v-for="(paramedic, nix) in item.paramedic_id" :key="nix">{{ paramedic.username }}</view>
						</uni-td>
						<uni-td align="center">{{ item.patient_name }}</uni-td>
						<uni-td align="center">{{ item.type | typeFilter }}</uni-td>
						<uni-td align="center">{{ item.service_location | typeLocalFilter }}</uni-td>
						<uni-td align="center"><el-tag :type="item.status|tagFilter" v-if="item.status">{{ item.status | statusFilter }}</el-tag></uni-td>
						<uni-td align="center">{{ item.patient_age }}</uni-td>
						<uni-td align="center">{{ item.tel }}</uni-td>
						<uni-td align="center">{{ item.total_price }}</uni-td>
						<uni-td align="center">{{ item.start_date }}</uni-td>
						<uni-td align="center">{{ item.end_date }}</uni-td>
						<uni-td align="center">{{ item.arrange_day }}</uni-td>
						<uni-td align="center">{{ item.arrange_hour }}</uni-td>
						<uni-td align="center">{{ item.day_sum }}</uni-td>
						<uni-td align="center">{{ item.hour_sum }}</uni-td>
						<uni-td align="center">{{ item.start_hour }}</uni-td>
						<uni-td align="center">{{ item.end_hour }}</uni-td>
						<uni-td align="center">{{ item.pay_type | paytTypeFilter }}</uni-td>
						<uni-td align="center">{{ item.platform }}</uni-td>
						<uni-td align="center">{{ item.create_time }}</uni-td>
						<uni-td align="center">{{ item.update_time }}</uni-td>
						<uni-td align="center">{{ item.paid_time }}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button v-if="item.status ===4||item.status ===5||item.status ===6" @click="hadleCheck(item)" class="uni-button"  type="warning"size="mini" >审核</button>
								<button @click="navigateTo('./detail?id=' + item._id)" class="uni-button" size="mini" type="primary">明细</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- 审核操作 -->
		<view>
			<el-dialog title="审核" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
				<el-form :model="checkForm"  :rules="rules" ref="checkForm">
					<el-form-item label="订单金额" :label-width="formLabelWidth" prop="total_price">
						<span>{{currtRows.total_price}}</span>
					</el-form-item>
					<el-form-item label="取消类型" :label-width="formLabelWidth" prop="statusp">
						<span>{{currtRows.status|statusFilter}}</span>
					</el-form-item>
					<el-form-item label="取消原因" :label-width="formLabelWidth" prop="cancel_reason">
						<span>{{currtRows.cancel_reason}}</span>
					</el-form-item>
					<el-form-item label="审核状态" :label-width="formLabelWidth"  prop="status">
						<el-radio-group v-model="checkForm.status">
							<el-radio :label="4">同意取消并退款</el-radio>
							<el-radio :label="2">审核拒绝【退回服务中】</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="退款金额" v-if="checkForm.status===4" :label-width="formLabelWidth" prop="refund_price">
						<el-input v-model="checkForm.refund_price" style="width:400px" placeholder="退款金额" type="number" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="审核原因" :label-width="formLabelWidth" prop="check_desc">
						<el-input v-model="checkForm.check_desc" :rows="5" placeholder="审核原因" style="width:400px" type="textarea" autocomplete="off"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="checkSubmit('checkForm')">确 定</el-button>
				</div>
			</el-dialog>
		</view>
	</view>
</template>

<script>
const db = uniCloud.database();
// 表查询配置
const dbCollectionName = 'orders,uni-id-users,hospitals';
const dbOrderBy = 'created_at desc'; // 排序字段
const dbSearchFields = ['patient_name']; // 支持模糊搜索的字段列表
// 分页配置
const pageSize = 15;
const pageCurrent = 1;
const typeMap = { 0: '到全天服务', 1: '时段服务' };
const typeLocalMap = { 0: '到医院服务', 1: '到家服务' };
const filTag = {
	'-1':'',
	0: 'success',
	1: 'info',
	2: 'warning',
	3: 'danger',
	4: 'danger',
	5: 'success',
	6: 'warning',
};
const filtMap = {
	'-1':'待支付',
	0: '已评论（订单结束）',
	1: '已付款（待服务）',
	2: '服务中',
	3: '服务结束',
	4: '已取消',
	5: '护工发起取消',
	6:'用户发起取消'
};//订单状态，0:已评论（订单结束），1:已付款（待服务），2:服务中，3:服务结束，4:已取消，5:护工发起取消，6:用户发起取消
const paytTypeMap = {
	0: '微信支付',
	1: '支付宝支付'
};
const payPlatformMap = {
	0: 'h5',
	1: 'mp-weixin',
	2: 'mp-alipay',
	3: 'app-plus'
};
const fields ='_id,type,service_location,user_id{_id,username,nickname},paramedic_id{_id,username,nickname},hospital_id{name},patient_name,tel,ward,mark,total_price,start_date,end_date,status';
export default {
	filters: {
		typeFilter(type) {
			//0:到全天服务，1:时段服务
			return typeMap[type];
		},
		tagFilter(type){
			return filTag[type];
		},
		statusFilter(type) {
			return filtMap[type];
		},
		typeLocalFilter(type) {
			return typeLocalMap[type];
		},
		paytTypeFilter(type) {
			return paytTypeMap[type];
		},
	},
	data() {
		return {
			formDataId:null,
			formLabelWidth: '120px',
			dialogFormVisible:false,
			typeMap: typeMap,
			typeLocalMap: typeLocalMap,
			filtMap: filtMap,
			paytTypeMap: paytTypeMap,
			payPlatformMap: payPlatformMap,
			fields: fields,
			query: {
				keyword:null,
				type:null,
				service_location:null,
				status:null,
				pay_type:null,
			},
			where: '',
			orderby: dbOrderBy,
			collectionName: dbCollectionName,
			options: {
				pageSize,
				pageCurrent
			},
			dialogFormVisible: false,
			checkForm: {
				status: null,
				refund_price:null,
				check_desc: null
			},
			rules: {
				status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
				refund_price:[{ required: true, message: '请填写退款金额', trigger: 'blur' }],
				check_desc: [{ required: true, message: '请填写审核原因', trigger: 'blur' }]
			},
			currtRows:{}//当前行数据
		};
	},
	methods: {
		getWhere() {
			let keyword = this.query.keyword;
			let s='';
			if (keyword) {
				keyword=keyword.trim();
				const queryRe = new RegExp(keyword, 'i');
				s=dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
			}
			let filed
			let filedArr=[]
			for(filed in this.query){
				if(filed!='keyword'&&this.query[filed]){
					filedArr.push(filed+'=='+parseInt(this.query[filed]))
				}
			}
			s=filedArr.join(' && ')
			return s
		},
		search() {
			const newWhere = this.getWhere();
			const isSameWhere = newWhere === this.where;
			this.where = newWhere;
			if (isSameWhere) {
				// 相同条件时，手动强制刷新
				this.loadData();
			}
		},
		loadData(clear = true) {
			this.$refs.udb.loadData({
				clear
			});
		},
		onPageChanged(e) {
			this.$refs.udb.loadData({
				current: e.current
			});
		},
		navigateTo(url) {
			uni.navigateTo({
				url,
				events: {
					refreshData: () => {
						this.loadData();
					}
				}
			});
		},
		// 多选处理
		selectedItems() {
			var dataList = this.$refs.udb.dataList;
			return this.selectedIndexs.map(i => dataList[i]._id);
		},
		//批量删除
		delTable() {
			this.$refs.udb.remove(this.selectedItems());
		},
		// 多选
		selectionChange(e) {
			this.selectedIndexs = e.detail.index;
		},
		confirmDelete(id) {
			this.$refs.udb.remove(id);
		},
		//审核操作
		hadleCheck(row){
			this.currtRows=row
			this.formDataId=row.id
			this.dialogFormVisible=true
			this.checkForm={
				status: null,
				refund_price:null,
				check_desc: null
			}
		},
		async checkSubmit(formName) {
			const that = this;
			let vali=false
			this.$refs[formName].validate(valid => {
				if (valid) {
					vali=true
				}
			});
			if(vali){
				//1退款TODO，2修改订单状态，3扣除护工信用分（护工取消才扣除 TODO ）
				if(this.checkForm.status===4){
					that.checkForm.refund_price=parseFloat(that.checkForm.refund_price)
					that.currtRows.refund_price=parseFloat(that.currtRows.total_price)
					if(that.checkForm.refund_price>that.currtRows.total_price){
						that.$message({
							showClose: true,
							message: '退款金额不能大于订单金额',
							type: 'error'
						});
						return false
					}
					let res = await unipay.refund({
					    outTradeNo: that.currtRows.no,//
					    outRefundNo: that.currtRows.no+"refund", // 支付宝可不填此项
					    totalFee:that.currtRows.total_price, // 订单总金额，支付宝可不填此项
					    refundFee: that.checkForm.refund_price, // 退款总金额
					})
					console.log(res,that.checkForm)
				}
				// 1退款
				console.log('------>',that.checkForm)
				// 修改订单状态
				db.collection(dbCollectionName)
					.doc(that.formDataId)
					.update(that.checkForm)
					.then(res => {
						that.$message({
							showClose: true,
							message: '恭喜你，审核成功',
							type: 'success'
						});
						that.dialogFormVisible = false;
						that.getOpenerEventChannel().emit('refreshData');
						setTimeout(() => uni.navigateBack(), 500);
					})
					.catch(err => {
						that.$message({
							showClose: true,
							message: err,
							type: 'error'
						});
					});
			}
		},
	}
};
</script>
<style lang="scss">
.suoluetu {
	width: 100rpx;
	height: 100rpx;
}
</style>
